<template>
  <div>
    <Card title="调价通知单新增" :bordered="false" dis-hover class="ivu-mt">
      <Row type="flex" style="flex-wrap: wrap">
        <Col span="8" style="height: 30px; line-height: 30px"
          >日期：<span>{{ formname.willChangeTime }}</span></Col
        >
        <Col span="8" style="height: 30px; line-height: 30px"
          >部门：<span>{{ formname.hrDepartmentName }}</span></Col
        >
        <Col span="8" style="height: 30px; line-height: 30px"
          >提交人：<span>{{ formname.createOperName }}</span></Col
        >
        <Col span="8" style="height: 30px; line-height: 30px"
          >发起区域：<span>{{ formname.hrAreaName }}</span></Col
        >
        <Col span="8" style="height: 30px; line-height: 30px"
          >主单据号：<span>{{ recodeNo }}</span></Col
        >
        <Col span="8" style="height: 30px; line-height: 30px"
          >供应商管理区域：{{ formname.supManagerHrAreaName }}
        </Col>
        <Col span="24" style="height: 30px; line-height: 30px; display: flex">
          供应商：{{ formname.supplierName }}
          <Button style="margin-left: 5px" @click="gongyingsh()"
            >选择供应商</Button
          >
        </Col>
      </Row>
      <Row style="margin-bottom: 10px; margin-top: 20px">
        <Button type="primary" @click="selectGhBt()">关联供货信息 </Button>

        <Button
          type="primary"
          style="margin-left: 20px"
          v-if="submit2"
          @click="saveInfo"
          :loading="SaveLoading"
          >保存
        </Button>
        <Button
          type="primary"
          style="margin-left: 20px"
          v-else
          @click="submit"
          :loading="submitLoading"
          >提交
        </Button>
      </Row>

      <Table
        border
        :loading="tableDataLoading"
        :columns="columns1"
        :data="baseTableData"
      >
        <template slot-scope="{ row, index }" slot="newUnitPrice">
          <InputNumber
            v-model="row.newUnitPrice"
            :active-change="false"
            :precision="2"
            type="number"
            placeholder="请输入.."
            :max="999999999"
            :min="0"
            @on-change="onChageNumRow($event, row, index)"
          />
        </template>
        <template slot-scope="{ row, index }" slot="reason">
          <Input
            v-model="row.reason"
            @on-change="onChageRow(row, index)"
            placeholder="请输入.."
          />
        </template>
        <template slot-scope="{ row }" slot="changeRatio">
          <span>{{ row.changeRatio }}</span>
        </template>
      </Table>
    </Card>
    <Modal
      v-model="modal1"
      width="1000"
      title="选择供应商"
    >
      <Row type="flex" align="middle">
        <span>供应商：</span>
        <Input
          v-model="value"
          placeholder="请输入供应商名称或供应商代码"
          style="width: 300px"
        />
        <Button type="primary" style="margin: 10px" @click="search"
          >查询
        </Button>
        <Button @click="search('reset')">清空</Button>
      </Row>
      <Table border :columns="columns2" :data="storeListData">
        <template slot-scope="{ row }" slot="action">
          <Button type="primary" size="small" @click="guanlianGysBt(row)"
            >关联
          </Button>
        </template>
      </Table>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <Page
          :total="totalNum"
          transfer
          show-total
          show-elevator
          show-sizer
          :current="nowPage"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
        />
      </div>
    </Modal>
    <Modal
      v-model="modal2"
      :closable="false"
      :mask-closable="false"
      width="1000"
      title="关联供货信息"
    >
      <Row type="flex" style="flex-wrap: wrap; position: relative">
        <Col
          span="6"
          style="display: flex; margin-bottom: 10px; line-height: 30px"
        >
          SUP编码：<Input
            v-model="formProductData.spuNo"
            style="width: 150px"
            placeholder="请输入.."
          />
        </Col>
        <Col
          span="6"
          style="display: flex; margin-bottom: 10px; line-height: 30px"
        >
          SKU编码：<Input
            v-model="formProductData.skuNo"
            style="width: 150px"
            placeholder="请输入.."
          />
        </Col>
        <Col
          span="6"
          style="display: flex; margin-bottom: 10px; line-height: 30px"
        >
          商品名称：<Input
            v-model="formProductData.productName"
            style="width: 150px"
            placeholder="请输入.."
          />
        </Col>
        <div style="position: absolute; bottom: 10px; right: 0">
          <Button type="primary" @click="searchBt">查询 </Button>
          <Button style="margin-left: 5px" @click="resetBt">清空 </Button>
        </div>
      </Row>
      <Tabs v-model="tabName" @on-click="handleClickTabs">
        <TabPane label="未关联" name="notAssociated">
          <Table
            border
            :loading="modalLoading"
            :columns="columns12"
            :data="wgProductData"
          >
            <template slot-scope="{ row }" slot="productName">
              <span>{{ row.supplyProductInfo.productName }}</span>
            </template>
            <template slot-scope="{ row }" slot="spuNo">
              <span>{{ row.supplyProductInfo.spuNo }}</span>
            </template>
            <template slot-scope="{ row }" slot="categoryPath">
              <span>{{ row.supplyProductInfo.categoryPath }}</span>
            </template>
            <template slot-scope="{ row }" slot="specDetailStr">
              <span>{{ row.supplyProductInfo.specDetailStr }}</span>
            </template>
            <template slot-scope="{ row }" slot="brandName">
              <span>{{ row.supplyProductInfo.brandName }}</span>
            </template>
            <template slot-scope="{ row, index }" slot="action">
              <Button
                type="success"
                size="small"
                style="margin: 3px 0"
                @click="linkProduct(row, index, '1')"
                >关联
              </Button>
            </template>
          </Table>
        </TabPane>
        <TabPane label="已关联" name="associated">
          <Table
            border
            :loading="modalLoading"
            :columns="columns12"
            :data="ygProductData"
          >
            <template slot-scope="{ row }" slot="productName">
              <span>{{ row.supplyProductInfo.productName }}</span>
            </template>
            <template slot-scope="{ row }" slot="spuNo">
              <span>{{ row.supplyProductInfo.spuNo }}</span>
            </template>
            <template slot-scope="{ row }" slot="categoryPath">
              <span>{{ row.supplyProductInfo.categoryPath }}</span>
            </template>
            <template slot-scope="{ row }" slot="specDetailStr">
              <span>{{ row.supplyProductInfo.specDetailStr }}</span>
            </template>
            <template slot-scope="{ row }" slot="brandName">
              <span>{{ row.supplyProductInfo.brandName }}</span>
            </template>
            <template slot-scope="{ row, index }" slot="action">
              <Button
                type="success"
                size="small"
                style="margin: 3px 0"
                @click="linkProduct(row, index, '0')"
                >取消
              </Button>
            </template>
          </Table>
        </TabPane>
      </Tabs>
      <div class="ivu-mt ivu-text-center">
        <Page
          :total="totalNumW"
          show-total
          show-sizer
          :current.sync="nowPage"
          @on-change="productTabsChang(tabName)"
          @on-page-size-change="handleChangePage"
        />
      </div>
      <Row slot="footer" style="justify-content: center">
        <Button type="primary" @click="handleCloseModal">返回表单</Button>
      </Row>
    </Modal>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters } from 'vuex';
import { SUPPLY_COLUMNS_1 } from '@/constants/supplyColumns';

export default {
  components: {},
  data () {
    return {
      SaveLoading: false,
      submitLoading: false,
      modalLoading: false,
      tableDataLoading: false,
      associatedRowList: new Map(),
      submit2: true,
      value: '',
      recodeNo: '',
      modal1: false,
      modal2: false,
      totalNum: 0,
      totalNumY: 0,
      totalNumW: 0,
      pageShow: 10,
      nowPage: 1,
      storeName: '',
      storeNo: '',
      supplyUuid: '',
      saleAreaName: '', // 供应商管理地区
      HrAreaName: '',
      cityCode: '',
      ygProductData: [],
      wgProductData: [],
      tabName: 'notAssociated',
      resdata: {
        freightPayer: '',
        mainLinkman: '',
        mobile: '',
        productionAddress: '',
        supMainCategoryId: '',
        supManagerHrAreaId: '',
        supManagerHrAreaName: '',
        supplierCode: '',
        supplierId: '',
        supplierName: ''
      },
      formname: {
        supplierName: '',
        supManagerHrAreaName: '',
        willChangeTime: '',
        supplierCode: '',
        hrDepartmentName: '',
        createOperName: '',
        hrAreaName: ''
      },
      formProductData: {
        spuNo: '',
        skuNo: '',
        productName: ''
      },
      columns12: [
        {
          title: '商品名称',
          slot: 'productName',
          fixed: 'left',
          minWidth: 150
        },
        {
          title: 'SPU编码',
          slot: 'spuNo',
          align: 'center',
          minWidth: 120
        },
        {
          title: 'SKU编码',
          key: 'skuNo',
          align: 'center',
          minWidth: 120
        },
        {
          title: '商品分类',
          slot: 'categoryPath',
          align: 'center',
          minWidth: 120
        },
        {
          title: '规格参数',
          slot: 'specDetailStr',
          align: 'center',
          minWidth: 120
        },
        {
          title: '品牌',
          slot: 'brandName',
          align: 'center',
          minWidth: 120
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 140
        }
      ],
      storeListData: [],
      columns2: SUPPLY_COLUMNS_1,
      productTableData: [],
      columns1: [
        {
          title: '商品名称',
          key: 'productName',
          align: 'center',
          minWidth: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          align: 'center',
          minWidth: 120
        },
        {
          title: 'SKU编码',
          key: 'skuNo',
          align: 'center',
          minWidth: 120
        },
        {
          title: '规格',
          key: 'spec',
          align: 'center',
          minWidth: 120
        },
        {
          title: '城市',
          key: 'cityName',
          align: 'center',
          minWidth: 120
        },
        {
          title: '商品管理区域',
          key: 'productManagerArea',
          align: 'center',
          minWidth: 150
        },
        {
          title: '原进价',
          key: 'oldUnitPrice',
          minWidth: 160
        },
        {
          title: '现进价',
          slot: 'newUnitPrice',
          minWidth: 160
        },
        {
          title: '浮动比例',
          slot: 'changeRatio',
          minWidth: 160
        },
        {
          title: '发起原因',
          slot: 'reason',
          align: 'center',
          minWidth: 120
        },
        {
          title: '落实原因',
          key: 'auditReason',
          align: 'center',
          minWidth: 120
        },
        /* {
          title: '调价单号',
          key: 'productUnit',
          align: 'center',
          minWidth: 120
        },
        {
          title: '调价区域',
          key: 'priceChangeAreaName',
          minWidth: 160
        }, */
        {
          title: '接收部门',
          key: 'purchasePrice',
          minWidth: 160
        }
      ],
      baseTableData: [],
      apiObj: {
        // 供应商列表
        getSupplers: {
          url: '/sysback/salepricechangeorder/getSupplers', // 接口地址
          type: 'get' // 接口请求类型
        },
        // 获取关联/未关联列表
        salepricerule: {
          url: '/sysback/supplyareaprice/getSkuPager', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 保存
        saveBasicInfo: {
          url: '/sysback/salepricechangeorder/batchAdd', // 接口地址
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  created () {},
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  methods: {
    // 查询 清空
    search (type) {
      let that = this;
      if (type == 'reset') {
        that.value = '';
      } else {
        this.initData();
      }
    },
    // 切换页码
    changePage (e) {
      this.nowPage = e;
      this.initData();
    },

    // 切换条数
    changePageSize (e) {
      this.pageShow = e;
      this.nowPage = 1;
      this.initData();
    },
    gongyingsh () {
      this.modal1 = true;
      this.nowPage = 1;
      this.pageShow = 10;
      this.initData();
    },
    initData () {
      let data = {
        supplyName: this.value,
        supplyNo: '',
        nowPage: this.nowPage,
        pageShow: this.pageShow
      };
      // 开始请求列表
      ApiRequest(
        this.apiObj.getSupplers.url,
        this.apiObj.getSupplers.type,
        data,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          this.storeListData = res.retData.results;
          this.totalNum = res.retData.totalNum;
        }
      });
    },
    searchBt () {
      this.nowPage = 1;
      this.pageShow = 10;
      this.selectGhBt();
    },
    resetBt () {
      this.formProductData.spuNo = '';
      this.formProductData.skuNo = '';
      this.formProductData.productName = '';
      this.nowPage = 1;
      this.pageShow = 10;
      this.selectGhBt();
    },
    // 选择供货信息
    selectGhBt () {
      let skuNoList = this.getRowListFn().map((value) => {
        return value.skuNo;
      });
      if (this.resdata.supplierCode === '') {
        this.$Message.error('请先选择供应商');
      } else {
        this.modal2 = true;
        let searchParam = [
          {
            name: 'spuNo',
            value: this.formProductData.spuNo
          },
          {
            name: 'skuNo',
            value: this.formProductData.skuNo
          },
          {
            name: 'productName',
            value: this.formProductData.productName
          },
          {
            name: 'spuNo_q',
            value: 'EQ'
          },
          { name: 'productName_q', value: 'Like' },
          { name: 'skuNo_q', value: 'EQ' }
        ];
        if (this.tabName === 'notAssociated') {
          searchParam.push(
            {
              name: 'skuNoNotInListStr',
              value: skuNoList.join(',')
            },
            {
              name: 'skuNoNotInListStr_q',
              value: 'NotIN'
            }
          );
        } else {
          searchParam.push(
            {
              name: 'skuNoListStr',
              value: skuNoList.join(',')
            },
            {
              name: 'skuNoListStr_q',
              value: 'IN'
            }
          );
        }
        let data = {
          nowPage: this.nowPage,
          pageShow: this.pageShow,
          searchParam: JSON.stringify(searchParam)
        };
        // 开始请求列表
        this.cityCode = '0';
        if (skuNoList.length === 0 && this.tabName === 'associated') {
          this.ygProductData = [];
          return;
        }
        let { url, type } = this.apiObj.salepricerule;
        this.modalLoading = true;
        ApiRequest(
          `${url}?supplyUuid=${this.resdata.supplierCode}&cityCode=${this.cityCode}`,
          type,
          data,
          false
        )
          .then((res) => {
            if (res.retStatus === '1') {
              this.modalLoading = false;
              this.productTableData = res.retData;
              this.tabName === 'notAssociated'
                ? (this.wgProductData = res.retData.results)
                : (this.ygProductData = res.retData.results);
              this.totalNumW = res.retData.totalNum;
              this.submit2 = true;
            } else {
              this.modalLoading = false;
              this.wgProductData = [];
              this.ygProductData = [];
              this.totalNumW = res.retData.totalNum;
            }
          })
          .catch(() => {
            this.modalLoading = false;
          });
      }
    },
    // 关联/取消关联商品
    linkProduct (row, index, type) {
      if (type === '1') {
        // 关联操作
        this.associatedRowList.set(row.uuid, row);
      } else {
        this.ygProductData.forEach((value) => {
          if (value.skuNo === row.skuNo) {
            this.associatedRowList.delete(value.uuid);
          }
        });
      }
      this.$nextTick(() => {
        this.selectGhBt();
      });
    },
    getRowListFn () {
      let values = this.associatedRowList.values();
      let rowList = [];
      for (let item of values) {
        rowList.push(item);
      }
      return rowList;
    },
    handleClickTabs () {
      this.nowPage = 1;
      this.pageShow = 10;
      this.selectGhBt();
    },
    // 关闭关联商品弹框
    handleCloseModal () {
      this.ygProductData = this.getRowListFn();
      let curBtnId = getBtnsId('查询');
      sessionStorage.setItem('button', curBtnId);
      let data = this.ygProductData;
      this.tableDataLoading = true;
      ApiRequest(
        `/sysback/salepricechangeorder/prepare?supplyUuid=${this.resdata.supplierCode}`,
        'post',
        data
      )
        .then((res) => {
          if (res.retStatus === '1') {
            this.tableDataLoading = false;
            res.retData.forEach((element) => {
              element.newUnitPrice = element.oldUnitPrice;
              element.changeRatio = 0;
            });
            this.baseTableData = res.retData;
          } else {
            this.tableDataLoading = false;
          }
        })
        .catch(() => {
          this.tableDataLoading = false;
        });
      this.modal2 = false;
    },
    // 关联供应商
    guanlianGysBt (row) {
      this.modal1 = false;
      this.formname.supplierName = row.supplierName;

      this.formname.supManagerHrAreaName = row.supManagerHrAreaName;
      this.formname.willChangeTime = this.getNowTime();
      this.formname.supplierCode = row.supplierCode;
      this.resdata.supplierCode = row.supplierCode;
      if (this.formname.supplierCode !== '') {
        let data = {
          userId: this.formname.supplierCode
        };
        ApiRequest(
          '/sysback/salepricechangeorder/getUserInfo?userId=' +
            this.formname.supplierCode,
          'post',
          data,
          false
        ).then((res) => {
          this.formname.hrDepartmentName = res.retData.hrDepartmentName;
          this.formname.createOperName = res.retData.userName;
          this.formname.hrAreaName = res.retData.hrAreaName;
        });
      }
    },

    productTabsChang (name) {
      this.tabName = name;
      this.selectGhBt();
    },
    // 提交信息
    saveInfo () {
      if (
        this.baseTableData === null ||
        this.baseTableData === undefined ||
        this.baseTableData.length === 0
      ) {
        this.$Message.error('数据为空,请关联供货信息');
        return false;
      } else {
        let isOk = true;
        this.baseTableData.forEach((element) => {
          if (
            element.newUnitPrice === '' &&
            element.newUnitPrice === null &&
            element.newUnitPrice === undefined
          ) {
            isOk = false;
            return;
          }
          if (
            element.reason === '' &&
            element.reason === null &&
            element.reason === undefined
          ) {
            isOk = false;
          }
        });
        if (!isOk) {
          this.$Message.error('请确保列表信息填写完整!');
        }
        let baseTableData = [];
        this.baseTableData.forEach((element) => {
          let obj = {
            ...element,
            ...this.formname,
            willChangeTime: this.getNowTime()
          };
          baseTableData.push(obj);
        });
        // 开始请求列表
        this.SaveLoading = true;
        ApiRequest(
          this.apiObj.saveBasicInfo.url +
            '?supplyUuid=' +
            this.resdata.supplierCode +
            '&cityCode=' +
            this.cityCode,
          this.apiObj.saveBasicInfo.type,
          baseTableData,
          false
        ).then((res) => {
          if (res.retStatus === '1') {
            this.submit2 = false;
            this.productTableData = res.retData;
            this.recodeNo = res.retData;
            this.SaveLoading = false;
            this.$Message.success('保存成功');
          } else {
            this.SaveLoading = false;
          }
        });
      }
    },
    submit () {
      this.submitLoading = true;
      ApiRequest(
        '/sysback/salepricechangeorder/submit?recordNo=' + this.recodeNo,
        'post'
      ).then((res) => {
        if (res.retStatus === '1') {
          this.$Message.success('提交成功');
          this.recodeNo = '';
          this.$router.go(-1);
          this.submitLoading = false;
        } else {
          this.submitLoading = false;
        }
      });
    },
    // 数据赋值处理
    onChageRow (row, index) {
      this.baseTableData[index] = row;
    },
    // 用于监听值的变化,计算数据
    onChageNumRow (e, row, index) {
      if (row.newUnitPrice == 0) {
        row.changeRatio = 0;
      } else {
        row.changeRatio = (
          parseFloat(row.newUnitPrice - row.oldUnitPrice) / row.oldUnitPrice
        ).toFixed(2);
      }
      this.baseTableData[index] = row;
    },
    handleChangePage (val) {
      this.pageShow = val;
      this.$nextTick(() => {
        this.productTabsChang(this.tabName);
      });
    },
    getNowTime () {
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? '0' + MM : MM;
      let d = date.getDate();
      d = d < 10 ? '0' + d : d;
      let h = date.getHours();
      h = h < 10 ? '0' + h : h;
      let m = date.getMinutes();
      m = m < 10 ? '0' + m : m;
      let s = date.getSeconds();
      s = s < 10 ? '0' + s : s;
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
    }
  }
};
</script>
